var amapFile = require('libs/amap-wx.js');
var config = require('config.js');
var util = require('network_util.js');
var commonjs = require('common.js');
var _cityName = "";

//系统初始化
function Init(cityName) {
  console.log("base.Init.cityName = " + cityName);
  getRegeo(cityName);
}

function getRegeo(cityName) {
  if (cityName != "") {
    _cityName = cityName;
    getCityId(cityName);
  } else {
    var key = config.aMapKey;
    var myAmapFun = new amapFile.AMapWX({ key: key });
    myAmapFun.getRegeo({
      iconPath: "../../images/marker.png",
      iconWidth: 22,
      iconHeight: 32,
      success: function (data) {
        console.log("getRegeo.data: ");
        console.log(data);
        cityName = data[0].regeocodeData.addressComponent.city;
        // that.setData({ localCityName: cityName });
        // that.setData({ localCityName:  "长沙市"});
        _cityName = cityName;
        wx.setStorage({
          key: "localCityName",
          data: cityName,
          success: function () {
            //3. 获取城市ID
            getCityId(cityName);
          }
        })
      },
      fail: function (info) {
        // wx.showModal({title:info.errMsg})
        console.log(info);
      },
      complete: function (ff) {
        console.log(ff);
      }
    })
  }
}

function getCityId(cityName) {
  //2.获取城市列表
  util._get(config.fromCityList,
    function (res) {
      console.log("base.get.fromCityList success");
      // console.log(res);
      for (var i = 0; i < res.data.data.length; i++) {
        var currCityName = cityName.replace("市", "");
        if (currCityName == res.data.data[i].cityName) {
          // that.setData({ cityId: res.data.data[i].id });
          var cityId = res.data.data[i].id;
          wx.setStorage({
            key: cityName + "_cityId",
            data: cityId,
          })
          //4. 获取地区（航站楼列表）
          getTerminalList(cityId);
          break;
        }
      }
    }, function (res) {
      console.log("base.get.fromCityList fail");
      // console.log(res);
    })

}
function getTerminalList(cityId) {
  util._get(config.searchAddress + "?cityId=" + cityId,
    function (res) {
      console.log(res);
      if (res.statusCode == 200) {
        if (res.data.code == 200) {
          console.log("airportName:" + res.data.data[0].airportName);
          wx.setStorageSync(_cityName + "_airportName", res.data.data[0].airportName);//缓存起来
          var terminals = commonjs.trim(res.data.data[0].terminalBuilding, ',').split(',');
          // console.log(terminals);
          wx.setStorageSync(_cityName + "_airportTerminals", terminals);//缓存起来
        } else {
          wx.showToast({
            title: res.data.msg + '(' + res.data.code + ')',
          })
        }
      } else {
        wx.showToast({
          title: '获取机场航站楼 系统错误：' + res.statusCode,
        })
      }
    })
}
module.exports = {
  Init: Init,
  getRegeo: getRegeo,
  getCityId: getCityId,
}